﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Sherwood.Content.Contracts;
using Sherwood.Security;

namespace Sherwood.Content.Tests
{
    [TestClass]
    public class UpdateRequestSigningTests
    {
        [TestMethod, ExpectedException(typeof(InvalidOperationException))]
        public void SignEmptyMessageThrowsExcpetion()
        {
            var request = new updateRecordsRequest();
            request.Sign(SampleClient.PrivateKey);
            Assert.IsTrue(request.VerifySignature(SampleClient.PublicKey));
        }

        [TestMethod]
        public void SignAndVerifySimpleMessage()
        {
            var request = new updateRecordsRequest();
            request.content = new updateRecordsRequestType.contentLocalType();
            request.content.record = new List<record>();
            request.content.record.Add(new record());
            request.Sign(SampleClient.PrivateKey);
            Assert.IsTrue(request.VerifySignature(SampleClient.PublicKey));
        }

        [TestMethod]
        public void SignAndVerifyModifiedMessage()
        {
            var request = new updateRecordsRequest();
            request.content = new updateRecordsRequestType.contentLocalType();
            request.content.record = new List<record>();
            request.content.record.Add(new record());
            request.Sign(SampleClient.PrivateKey);
            request.content.record.Add(new record());
            Assert.IsFalse(request.VerifySignature(SampleClient.PublicKey));
        }

        [TestMethod]
        public void SignAndVerifyMessageWithWhitespaceDifference()
        {
            var request = new updateRecordsRequest();
            request.content = new updateRecordsRequestType.contentLocalType();
            request.content.record = new List<record>();
            request.content.record.Add(new record());

            var rsa = Rsa.FromPrivateKey(SampleClient.PrivateKey);
            var message = "<content><record/></content>"; // <record/> instead of <record />. in other words, we assume that the xml we receive is perfectly formatted.
            request.client = new client();
            request.client.signature = rsa.SHA1Sign(message);

            Assert.IsFalse(request.VerifySignature(SampleClient.PublicKey));
        }
    }
}
